﻿#include "widget.h"
#include "ui_widget.h"

#include <QWebEngineView>
#include <QWebEngineSettings>

#include <QHostAddress>
#include "httpserver/qhttpserver.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    initHttpServer();
    initWebview();
}

Widget::~Widget()
{
    delete ui;
    delete web;
    delete server;
}

void Widget::initWebview()
{
    web = new QWebEngineView();
    QWebEnginePage *page = new QWebEnginePage(web);
    web->setPage(page);

    //打开网页插件支持
    web->settings()->setAttribute(QWebEngineSettings::PluginsEnabled, true);

    web->load(QUrl("http://localhost:7310/"));

    web->show();

    connect(web,&QWebEngineView::loadFinished,this,[this](bool ok){
      web->page()->runJavaScript(QString("showVersion(true)"));
      //可获取
      web->page()->runJavaScript("getVersion()",[](const QVariant &v){qDebug()<<v.toString();});
    });

}

void Widget::initHttpServer()
{
    server = new QHttpServer();
    QString urlBase;
    QString sslUrlBase;

    server->route("/", QHttpServerRequest::Method::Get, [] () {
          return  QHttpServerResponse::fromFile("index/index.html");
      });
      server->route("/", [] (const QString &file,const QHttpServerRequest &req) {
          qDebug()<<"url:"<<req.url();
          return QHttpServerResponse::fromFile("index/" + file);
      });
      server->route("/assets/", [] (const QString &file,const QHttpServerRequest &req) {
          qDebug()<<"url:"<<req.url();
          return QHttpServerResponse::fromFile("index/assets/" + file);
      });

      quint16 port = server->listen(QHostAddress::Any,7310);
      if (!port){
          qWarning() << QString("error:Http server listen [%1] failed").arg(port);
      }
      urlBase = QStringLiteral("http://localhost:%1/").arg(port);
      qDebug()<<"urlBase:"<<urlBase;
}

